package main

import (
	"fmt"
	"reflect"
	"unsafe"
)

func BytesToString(b []byte) string {
	// 首先把 []byte -> unsfae.Pointer
	// unsafe.Pointer -> string指针类型
	// 取得对应地址上的值并返回
	return *(*string)(unsafe.Pointer(&b))

}

// 共享底层存储
func StringToBytes(s string) []byte {
	sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
	bh := reflect.SliceHeader{
		Data: sh.Data,
		Len:  sh.Len,
		Cap:  sh.Len,
	}
	return *(*[]byte)(unsafe.Pointer(&bh))
}

func main() {
	var s = "hello"
	var b = []byte("hello")
	fmt.Println(s)         // hello
	fmt.Println(string(b)) // hello
	println("[]byte -> string")
	fmt.Println(BytesToString(b))
	println("string -> []byte")
	fmt.Println(string(StringToBytes(s)))

}
